package com.icss.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.icss.util.DBUtil;

public class BaseDao {
	//连接数据库
	public static Connection getConn() {
		//1、创建连接对象
		Connection conn = null;
		try {
			//2、注册驱动
			Class.forName(DBUtil.DRIVER);
			//3、连接数据库
			conn = DriverManager.getConnection(DBUtil.URL, DBUtil.USER, DBUtil.PASS);
		} catch (ClassNotFoundException e) {
			System.out.println("注册驱动失败"+e.getMessage());
		} catch (SQLException e) {
			System.out.println("连接数据库失败"+e.getMessage());
		}
		return conn;
	}
	//关闭
	public static void closeAll(Connection conn,PreparedStatement ps,ResultSet rs) {
		if(rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(ps != null) {
			try {
				ps.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	//增删改
	public static boolean modify(String sql,Object...obj) {
		Connection conn = getConn();
		PreparedStatement ps = null;
		int result = 0;
		try {
			ps = conn.prepareStatement(sql);
			for(int i = 0;i < obj.length;i++) {
				ps.setObject(i+1,obj[i]);
			}
			//影响行
			result = ps.executeUpdate();
		} catch (SQLException e) {
			System.out.println("sql语句异常"+e.getMessage());
		}finally {
			closeAll(conn, ps, null);
		}
		return result > 0 ? true : false;
	}
}
